package com.admin.action.lend_book_action;

import com.admin.Action;

import com.admin.service.bookservice.BookServiceImpl;

import com.admin.service.lend_book_service.LendOperateImpl;
import com.pojo.BooksBean;
import com.pojo.BorInfoBean;
import com.pojo.BorrowerBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 根据用户的idCard和书的bookId借书
 */
public class LendBookAction extends Action {
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        PrintWriter out=response.getWriter();
        //判断是否是当前操作员

        HttpSession session = request.getSession();
//        System.out.println(session.getAttribute("adminInfo"));
        if(session.getAttribute("adminInfo")==null){
            out.println("<script>parent.window.location.href='error.html';</script>");
            return;
        }


        boolean bool=false;
        String bookId = request.getParameter("id");
        String idCard = request.getParameter("card");
        //根据idcard查询用户id
        LendOperateImpl lendOperate=new LendOperateImpl();
        BorrowerBean borrowerBean =lendOperate.queryUserIdByIdCard(idCard);

        System.out.println("用户id"+borrowerBean.getUserId());

        //要插入一条书籍库存，存在状态，借阅价格，归还时间，书籍id，用户id

        //根据书籍id查阅书籍信息
        BookServiceImpl booksService=new BookServiceImpl();
        BooksBean bookInfo=booksService.queryBookInfoByBookId(bookId);

        //创建当前时间
        Date date = new Date();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE,7);//加7天代表归还时间
        Date time = calendar.getTime();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String repayTime = simpleDateFormat.format(time);

        BorInfoBean borInfoBean = new BorInfoBean();
        borInfoBean.setBookId(Long.valueOf(bookId));
        borInfoBean.setBorId(borrowerBean.getUserId());
        borInfoBean.setPrice(bookInfo.getBorrowPrice());
        borInfoBean.setRepayDate(repayTime);//归还时间
        borInfoBean.setState("未归还");

        bool=lendOperate.addLendInfo(borInfoBean);

        System.out.println("插入"+bool);


        //books表要修改库存

        //借阅者要减少可借阅数量和余额
//        根据借阅者id修改用户的金额和库存
        boolean bool2=lendOperate.reduceUserStockAndBalance(borrowerBean.getUserId(),bookInfo.getBorrowPrice());

        System.out.println("修改金额;"+bool2);

        if(bool2){
            boolean bool1=booksService.updateStock(bookId);//减少库存
            System.out.println("库存减少"+bool1);
            if(bool1){
                out.print("借阅成功");
            }
        }else {

            out.print(false);
        }















    }
}
